#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @Time    : 2018/1/24 15:18
# @Author  : RNone
import datetime
import json
from xml.dom.minidom import parseString

import xlrd
import xlwt
from dicttoxml import dicttoxml
from xlutils.copy import copy


class excel_control():
	def excel_read(self, path, index=0):
		'''
		读取excel文件，并返回sheet
		:param path: 文件路径
		:param index: 工作表索引
		:return: sheet对象
		'''
		workBook = xlrd.open_workbook(path)
		sheet = workBook.sheets()[index]
		return sheet

	def excel_revise(self, path, row, column, data):
		'''
		修改指定位置内容
		:param path: 文件路径
		:param row: 横坐标索引
		:param column: 纵坐标索引
		:param data: 修改内容
		:return: 
		'''
		rb = xlrd.open_workbook(path)
		rs = rb.sheet_by_index(0)
		wb = copy(rb)
		ws = wb.get_sheet(0)
		ws.write(int(row), int(column), data)
		wb.save(path)

	def excel_write_link(self, wb, row, column, data):
		n = "HYPERLINK"
		ws = wb.get_sheet(0)
		ws.write_merge(
			int(row), int(row),
			int(column), int(column),
			xlwt.Formula(n + '("%s";"结果")' % (data)))
		return wb

	def excel_write(self, wb, row, column, data):
		ws = wb.get_sheet(0)
		ws.write(int(row), int(column), data)
		return wb

	def readbook_to_writebook(self, path):
		rb = xlrd.open_workbook(path)
		wb = copy(rb)
		return wb

	def case_to_dict(self, keys, values):
		'''
		将用例字典化
		:param keys: 用例的标题列表
		:param values: 用例的值列表
		:return: 用例的标题与值对应的字典
		'''
		case = {}
		for i in range(len(keys)):
			if isinstance(values[i], float):
				values[i] = int(values[i])
			case[keys[i]] = values[i]
		return case

	def params_to_dict(self, case):
		'''
		将用例中parms字典化并数字整型化
		:param case: 用例字典
		:return: 用例字典
		'''
		params = {}
		if '{' in case['params']:
			data = ''
			data = data.join(case['params'].split('\n'))
			data = data.replace(' ', '')
			data = data.replace('\'', '\"')
			params = json.loads(data)
		else:
			temp = case['params'].split('\n')
			for i in temp:
				if i.split('=')[1].isdigit():
					value = int(i.split('=')[1])
				else:
					value = i.split('=')[1]
				params[i.split('=')[0]] = value
		case['params'] = params
		return case

	def case_to_dict_from_cases(self, keys, values):
		'''
		针对phone_api的用例字典化的全部流程，包括parms字典化和用例数字整型化
		:param keys: 用例的标题列表
		:param values: 用例的值列表
		:return: 用例的标题与值对应的字典
		'''
		case = self.case_to_dict(keys, values)  # 将用例参数取出，并用变量名匹配
		case = self.params_to_dict(case)  # 将参数字典化
		return case

	def result_output(self, case_dict):
		'''
		输出结果至result目录
		:param params: 包含测试结果的用例字典
		:return: 
		'''
		with open('./result/%s.txt' % (datetime.datetime.now().strftime('%Y-%m-%d')), 'a+') as f:
			f.write('[%s] : %s %s %s %s \n' % (
				datetime.datetime.now(), case_dict['id'], case_dict['title'], case_dict['result'],
				case_dict['timeConsuming']))

	def xml_format(self, data):
		data_xml = dicttoxml(data, attr_type=False)
		try:
			data_xml = parseString(data_xml)
		except Exception as e:
			# 由于部分数据乱码，暂时先将乱码数据置为空
			if 'data' in data:
				for i in data['data']:
					i['post_content'] = ''
			return self.xml_format(data)
		data_xml = data_xml.toprettyxml()
		return data_xml

	def xml_output(self, case_dict):
		filename = './xml_result/[%s][%s][%s].xml' % (
			datetime.datetime.now().strftime('%Y-%m-%d %H_%M_%S'),
			case_dict['id'], case_dict['title'])
		with open(filename, 'w') as f:
			xml_data = self.xml_format(case_dict['response'])
			f.write(xml_data)
		return filename
